package cz.zcu.fav.rat.managed.bean;

import java.io.IOException;
import java.io.OutputStream;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpServletResponse;

import cz.zcu.fav.rat.qrcode.ObjectQRCodeGenerator;

@ManagedBean(name = "qrprinterbean")
@RequestScoped
public class QRPrinterBean
{
	@ManagedProperty(value = "#{param.id}")
	Integer id;

	public void render(ComponentSystemEvent event) throws IOException
	{
		printPDF();
	}

	private void printPDF() throws IOException
	{
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		HttpServletResponse response = (HttpServletResponse) externalContext
				.getResponse();
		response.reset();
		response.setContentType("application/pdf");
		OutputStream browserStream;

		browserStream = response.getOutputStream();
		ObjectQRCodeGenerator gen = SpringBeanFactory.getInstance().getBean(
				ObjectQRCodeGenerator.class);
		gen.createPDF(browserStream, id);
		browserStream.close();

		facesContext.responseComplete();
	}

	public void setId(Integer id)
	{
		this.id = id;
	}

}
